from app.index import indexbp
from flask import render_template,request,make_response
import env_config
import json
from app.utils.util import MyCusEncoder
from app.forms import LoginForm
from app.models import Admin
from flask_login import current_user, login_user

@indexbp.route('/')
@indexbp.route('/index')
def index():
    site={}
    ip = request.remote_addr.replace('.','')
    site={'ip':ip}
    return render_template('index.html',title='我的',site = site,enlist = env_config.EN_LIST)


@indexbp.route('/welcome', methods=['GET', 'POST'])
def welcome():
    return render_template('welcome.html')

@indexbp.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        result={'code':0}
        res = make_response()
        user = Admin.query.filter_by(username=form.username.data).first()
        print(user)
        if user is None or not user.check_password(form.password.data):
            result['message'] = '登录失败，用户名或密码不正确'
        else:
            result['code'] = 1
            result['message'] = '登录成功'
            user.username = form.username.data
            login_user(user)
        res.data=json.dumps(result, cls=MyCusEncoder)
        res.mimetype = 'application/json'
        return res

    return render_template('login.html',jumpurl=request.values.get('next','/',type=str),form = form)


